package com.lanou.managerLogin.order.dao;

import com.lanou.managerLogin.book.domain.Book;
import com.lanou.managerLogin.order.domain.Order;
import com.lanou.managerLogin.order.domain.OrderItem;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl implements OrderDao {

    private ComboPooledDataSource dataSource = new ComboPooledDataSource();

//    @Override
//    public List<Order> selectAllOrder() {
//        try {
//            Connection conn = dataSource.getConnection();
//            QueryRunner qr = new QueryRunner();
//            String sql = "select * from orders";
//            List<Order> orderList = qr.query(conn, sql, new BeanListHandler<Order>(Order.class));
//            conn.close();
//            return orderList;
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//        return new ArrayList<>();
//    }

    @Override
    public List<Order> selectOrder() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            QueryRunner runner = new QueryRunner();
            String sql = "select * from orders";
            List<Order> orderList = runner.query(conn, sql, new BeanListHandler<>(Order.class));
            conn.close();
            return orderList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public List<OrderItem> selectOrderItem(String oid) {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            QueryRunner runner = new QueryRunner();
            String sql = "select * from orderitem where oid = ?";
            List<OrderItem> orderItemList = runner.query(conn, sql, new BeanListHandler<>(OrderItem.class), oid);
            conn.close();
            return orderItemList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public Book oneBook(String bid) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            Book query = qr.query(conn, "select * from book where bid = ?", new BeanHandler<Book>(Book.class), bid);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new Book();

    }
}
